﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kxcxw.Data;
using System.Collections;
using kxcxw.Data.Entities;
using System.Web.Security;
using System.IO;
using kxcxw.Business;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using Webdiyer.WebControls.Mvc;
using KXCXW.Web.CommonClass;
using kxcxw.Data.Common;
using System.Data;
using KXCXW.Web.Models;
using System.Web.Caching;

namespace KXCXW.Web.Controllers
{
    public class PublishInfoController : Controller
    {
        //
        // GET: /PublishInfo/
        static Dictionary<string, string> PicNameDictionary = new Dictionary<string, string>();
        private KXCXWDBContext db = new KXCXWDBContext();
        private CommonRepositories comm = new CommonRepositories();
        private ImgHelper conlist = null;

        private void initImgPoth()
        {
            string rootpath = Server.MapPath("~/Content/xml/imgconfig.xml");
            conlist = new ImgHelper(rootpath);
        }

        [Authorize]
        public ActionResult MyInfoList(string sortOrder, string searchString, int? type, int? page = 1)
        {
            ViewData["dlCount"] = "0";
            ViewData["type"] = type;

            #region 我的信息
            string userid = Membership.GetUser().ProviderUserKey.ToString();
            ViewBag.DateSortParm = sortOrder == "Date" ? "Date desc" : "Date";
            var publichinformation = from s in db.PublichInformations where s.PublishID == userid && s.InfoType == (type == null ? 1 : type) select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                publichinformation = publichinformation.Where(s => s.Title.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "Date":
                    publichinformation = publichinformation.OrderBy(s => s.PublishDate);
                    break;
                default:
                    publichinformation = publichinformation.OrderByDescending(s => s.PublishDate);
                    break;
            }
            int pageSize = 10;
            int pageIndex = page ?? 1;
            PagedList<PublichInformation> temp = publichinformation.ToPagedList(pageIndex, pageSize);
            if (Request.IsAjaxRequest())
                return PartialView("List", temp);
            #endregion
            return View(temp);
        }

        [Authorize]
        public ActionResult WebShopEdit(string id)
        {
            var sl = comm.getTypeListByIdForDropDownList(DataConstants.PromotionTypeItemID);
            var s2 = comm.getTypeListByIdForDropDownList(DataConstants.SourceTypeItemID);

            CommonRepositories cr = new CommonRepositories();
            PublichInformation pinfo = (from q in db.PublichInformations
                                        where q.InformationID == id
                                        select q).FirstOrDefault();

            ViewBag.PromotionTypeList = new SelectList(sl, "Id", "Name", pinfo.PromotionType);
            ViewBag.SourceList = new SelectList(s2, "Id", "Name", pinfo.InfoSource);

            var s3 = comm.getRootProductCategoryList();
            if (pinfo.ItemDeitalID != null)
            {
                SysItemDetial sid = (from q in db.SysItemDetials
                                     where q.ItemDeitalID == pinfo.ItemDeitalID
                                     select q).FirstOrDefault();
                var s4 = comm.getProductCategoryListById(sid.ItemDeitalPID);
                ViewBag.rootCategoryList = new SelectList(s3, "Id", "Name", sid.ItemDeitalPID);
                ViewBag.CategoryList = new SelectList(s4, "ItemDeitalID", "itemDetialName", sid.ItemDeitalID);
            }
            else
            {
                ViewBag.rootCategoryList = new SelectList(s3, "Id", "Name");
                List<SelectListItem> Items = new List<SelectListItem>();
                Items.Add(new SelectListItem { Value = "", Text = "请选择类别" });
                ViewBag.CategoryList = Items;
            }
            ViewBag.UserKey = Membership.GetUser().ProviderUserKey.ToString();
            if (string.IsNullOrEmpty(pinfo.Other)) pinfo.Other = "输入赠品名称";
            return View(pinfo);
        }

        public JsonResult QY(string ParentID)
        {
            var list = comm.getProductCategoryListById(ParentID);
            List<SelectListItem> Items = new List<SelectListItem>();
            Items.Add(new SelectListItem { Value = "", Text = "请选择类别" });
            foreach (SysItemDetial item in list)
            {
                Items.Add(new SelectListItem { Value = item.ItemDeitalID, Text = item.itemDetialName });
            }
            return Json(Items, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult EntityShopEdit(string id)
        {
            var sl = comm.getTypeListByIdForDropDownList(DataConstants.PromotionTypeItemID);
            var s2 = comm.getTypeListByIdForDropDownList(DataConstants.SourceTypeItemID);

            CommonRepositories cr = new CommonRepositories();
            PublichInformation pinfo = (from q in db.PublichInformations
                                        where q.InformationID == id
                                        select q).FirstOrDefault();

            ViewBag.PromotionTypeList = new SelectList(sl, "Id", "Name", pinfo.PromotionType);
            ViewBag.SourceList = new SelectList(s2, "Id", "Name", pinfo.InfoSource);

            var s3 = comm.getRootProductCategoryList();
            if (pinfo.ItemDeitalID != null)
            {
                SysItemDetial sid = (from q in db.SysItemDetials
                                     where q.ItemDeitalID == pinfo.ItemDeitalID
                                     select q).FirstOrDefault();
                var s4 = comm.getProductCategoryListById(sid.ItemDeitalPID);
                ViewBag.rootCategoryList = new SelectList(s3, "Id", "Name", sid.ItemDeitalPID);
                ViewBag.CategoryList = new SelectList(s4, "ItemDeitalID", "itemDetialName", sid.ItemDeitalID);
            }
            else
            {
                ViewBag.rootCategoryList = new SelectList(s3, "Id", "Name");
                List<SelectListItem> Items = new List<SelectListItem>();
                Items.Add(new SelectListItem { Value = "", Text = "请选择类别" });
                ViewBag.CategoryList = Items;
            }
            ViewBag.UserKey = Membership.GetUser().ProviderUserKey.ToString();
            if (string.IsNullOrEmpty(pinfo.Other)) pinfo.Other = "输入赠品名称";
            return View(pinfo);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Save(PublichInformation publichInformation)
        {
            if (ModelState.IsValid)
            {
                MembershipUser user = Membership.GetUser();
                string faceimg = Request.Form["faceRadio"];
                publichInformation.MapUrl = faceimg;
                publichInformation.PictureShow = AppendPicListXml(publichInformation.InformationID);
                db.Entry(publichInformation).State = EntityState.Modified;
                db.SaveChanges();
                TempData["status"] = "Success";
                return RedirectToAction("ReleaseSuccess", new { id = publichInformation.InformationID });
            }
            return RedirectToAction("ReleaseErroy");
        }

        [Authorize]
        public ActionResult Delete(string id, string searchString, string sortOrder, int page)
        {
            PublichInformation publichinformation = (from q in db.PublichInformations
                                                     where q.InformationID == id
                                                     select q).FirstOrDefault();
            publichinformation.Status = DataConstants.Deleted;
            db.Entry(publichinformation).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("MyInfoList", new { type = publichinformation.InfoType, sortOrder = sortOrder, searchString = searchString, page = page });
        }

        public ActionResult ReleaseSuccess(string id)
        {
            PublichInformation publichInformation = (from q in db.PublichInformations
                                                     where q.InformationID == id
                                                     select q).FirstOrDefault();
            return View(publichInformation);
        }

        public ActionResult ReleaseErroy()
        {
            return View();
        }
        [OutputCache(Duration = 900, VaryByParam = "*")]
        public ActionResult Other(string userId, int? typeId, string sortOrder, int? page = 1)
        {
            ViewData["ProductMenu"] = comm.getProductCategoryList();
            int typeInt = typeId != null ? Convert.ToInt32(typeId) : 1;
            ViewData["type"] = typeId != null ? typeId.ToString() : "";

            #region 跟据类别获得商品列表
            IQueryable<PublichInformation> infolist = comm.getProductListByUser(userId);

            if (typeId != null)
            {
                infolist = infolist.Where(q => q.InfoType == typeId);
            }
            ViewData["resultCount"] = infolist.Count();
            #region 筛选信息
            double highestPrice = 0;
            if (infolist != null && infolist.Count() > 0)
                highestPrice = Convert.ToDouble(infolist.Max(s => s.PresentPrice));
            ViewData["highestPrice"] = highestPrice;

            if (Request.QueryString["p"] != null)
            {
                string pvalue = Request.QueryString["p"].ToString();
                if (pvalue != "all")
                {
                    string[] arr = pvalue.Split('-');
                    decimal minPrice = Convert.ToDecimal(arr[0]);
                    infolist = infolist.Where(s => s.PresentPrice > minPrice);
                    if (arr[1] != "")
                    {
                        decimal maxPrice = Convert.ToDecimal(arr[1]);
                        infolist = infolist.Where(s => s.PresentPrice < maxPrice);
                    }
                }
            }
            if (Request.QueryString["d"] != null)
            {
                string dvalue = Request.QueryString["d"].ToString();
                if (dvalue != "all")
                {
                    string[] arr = dvalue.Split('-');
                    decimal minDiscount = Convert.ToDecimal(arr[0]);
                    if (arr.Length == 2)
                    {
                        decimal maxDiscount = Convert.ToDecimal(arr[1]);
                        infolist = infolist.Where(s => s.Discount >= minDiscount);
                        infolist = infolist.Where(s => s.Discount <= maxDiscount);
                    }
                    else
                    {
                        infolist = infolist.Where(s => s.Discount == minDiscount);
                    }
                }
            }
            #endregion
            #region 排序
            string[] orderarr = new string[] { "", "" };
            if (!string.IsNullOrEmpty(sortOrder))
                orderarr = sortOrder.Split('-');
            string orderFeild = "Date";
            string order = "Desc";

            orderFeild = orderarr[0];
            if (orderarr.Length == 1)
                order = "Asc";
            if (order == "Asc")
            {
                switch (orderFeild)
                {
                    case "Date":
                        infolist = infolist.OrderBy(s => s.PublishDate);
                        break;
                    case "Price":
                        infolist = infolist.OrderBy(s => s.PresentPrice);
                        break;
                    case "Discount":
                        infolist = infolist.OrderBy(s => s.Discount);
                        break;
                    default:
                        infolist = (infolist.OrderByDescending(p => p.PriorityLevel)
                            .ThenByDescending(p => p.TopDate)
                            .ThenByDescending(p => p.AlertDate)
                            .ThenByDescending(s => s.PublishDate));
                        break;
                }
            }
            else
            {
                switch (orderFeild)
                {
                    case "Date":
                        infolist = infolist.OrderByDescending(s => s.PublishDate);
                        break;
                    case "Price":
                        infolist = infolist.OrderByDescending(s => s.PresentPrice);
                        break;
                    case "Discount":
                        infolist = infolist.OrderByDescending(s => s.Discount);
                        break;
                    default:
                        infolist = (infolist.OrderByDescending(p => p.PriorityLevel)
                            .ThenByDescending(p => p.TopDate)
                            .ThenByDescending(p => p.AlertDate)
                            .ThenByDescending(s => s.PublishDate));
                        break;
                }
            }
            #endregion
            int pageSize = DataConstants.morePageSize; ;
            int pageIndex = page ?? 1;
            PagedList<PublichInformation> temp = infolist.ToPagedList(pageIndex, pageSize);
            if (Request.IsAjaxRequest())
                return PartialView("_SearchList", temp);
            #endregion

            #region 导购排行
            List<Daogou> daogoulist = comm.getDaoGouPopList(typeInt);
            ViewData["DaoGouPop"] = daogoulist.ToList<Daogou>();
            #endregion
            ViewData["user"] = comm.getUserById(userId);
            return View(temp);
        }

        private string AppendPicListXml(string infoId)
        {
            string oldXml = "";
            var info = comm.getInfoById(infoId);
            oldXml = (info != null && info.PictureShow != null ? info.PictureShow : "");
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            if (oldXml == "")
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<imgs>");
                if (PicNameDictionary.Count > 0 && PicNameDictionary[userKey] != "")
                {
                    foreach (string filename in PicNameDictionary[userKey].Split(','))
                    {
                        if (filename != "")
                            sb.Append(string.Format("<filename>{0}</filename>", filename));
                    }
                }
                sb.Append("</imgs>");
                return sb.ToString();
            }
            else
            {
                XmlDocument xmlImgs = new XmlDocument();
                xmlImgs.LoadXml(oldXml);
                XmlNode root = xmlImgs.SelectSingleNode("imgs");
                if (PicNameDictionary.Count > 0 && PicNameDictionary[userKey] != "")
                {
                    foreach (string filename in PicNameDictionary[userKey].Split(','))
                    {
                        XmlElement xn = xmlImgs.CreateElement("filename");
                        xn.InnerText = filename;
                        root.AppendChild(xn);
                    }
                }
                return xmlImgs.OuterXml;
            }
        }
        /// <summary>
        /// 删除缓存中的图片
        /// </summary>
        public void DeleteImgsInDic()
        {
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            if (PicNameDictionary.Count > 0 && PicNameDictionary[userKey] != "")
            {
                foreach (string filename in PicNameDictionary[userKey].Split(','))
                {
                    if (filename != "")
                    {
                        foreach (Img img in conlist.getImgConfigList())
                        {
                            DeletePic(img.foldname, filename);
                        }
                    }
                }
            }
        }
        public void RemovePicDic()
        {
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            PicNameDictionary.Remove(userKey);
        }
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="filedata"></param>
        /// <returns></returns>

        [HttpPost]
        public ActionResult UpLoad(HttpPostedFileBase filedata)
        {
            string userKey = Request.Form["userId"];
            string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            initImgPoth();
            foreach (Img img in conlist.getImgConfigList())
            {
                thumbnail_id = ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/" + ImgHelper.ImgRootUrl + img.foldname + "/"), thumbnail_id, img.width, img.height, filedata);
                Response.Write(thumbnail_id);
                Response.End();
            }
            if (PicNameDictionary.ContainsKey(userKey))
            {
                PicNameDictionary[userKey] = PicNameDictionary[userKey].ToString() + "," + thumbnail_id + ".jpg";
            }
            else
            {
                PicNameDictionary.Add(userKey, thumbnail_id + ".jpg" + ",");
            }
            return new EmptyResult();
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeletePic(HttpPostedFileBase filedata)
        {
            initImgPoth();
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            string id = Request.Form["id"];
            string infoid = Request.Form["infoid"];
            foreach (Img img in conlist.getImgConfigList())
            {
                DeletePic(img.foldname, id);
            }
            if (!comm.DeleteimgDataById(infoid, id))
            {
                if (PicNameDictionary.ContainsKey(userKey))
                {
                    string temp = PicNameDictionary[userKey].ToString();
                    temp = temp.Replace(id + ",", "");

                    PicNameDictionary[userKey] = PicNameDictionary[userKey].ToString().Replace(id + ",", "");
                }
            }

            return new EmptyResult();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ClearePicDictionary()
        {
            if (TempData["status"] == null || TempData["status"].ToString() != "Success")
                DeleteImgsInDic();//清除缓存中的图片
            RemovePicDic();//清除图片缓存
            return new EmptyResult();
        }

        #region 删除垃圾图片
        private void DeletePic(string folder, string picName)
        {
            initImgPoth();
            string url = Server.MapPath("~/" + ImgHelper.ImgRootUrl + folder + "/" + picName);
            if (System.IO.File.Exists(url))
            {
                System.IO.File.Delete(url);
            }
        }
        #endregion

        [Authorize]
        [HttpPost]
        public string SetTop(string id)
        {
            var info = (from q in db.PublichInformations
                        where q.InformationID == id
                        select q).FirstOrDefault();
            info.PriorityLevel = 1;
            info.TopDate = DateTime.Now;
            info.AlertDate = DateTime.Now;
            db.Entry(info).State = EntityState.Modified;
            if (db.SaveChanges() > 0)
                return "true";
            return "置顶错误请刷新后重试！";
        }

        [Authorize]
        [HttpPost]
        public string SetSpecial(string id,string type)
        {
            MembershipUser user = Membership.GetUser();
            string userKey = user.ProviderUserKey.ToString();
            int specount = (from q in db.PublichInformations
                            where q.AreaType == type
                            && q.PublishID == userKey
                            select q).Count();
            if(specount>=DataConstants.MaxSpecialNum)
                return "精品区和特品区每个用户最多可以推荐5个！";
            var info = (from q in db.PublichInformations
                        where q.InformationID == id
                        select q).FirstOrDefault();
            info.AreaType = type;
            info.AlertDate = DateTime.Now;
            db.Entry(info).State = EntityState.Modified;
            if (db.SaveChanges() > 0)
                return "true";
            return "推荐错误请刷新后重试！";
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
